//
//  NetWorkRequestManager.m
//  NetWorkRequestDemo
//
//  Created by 卢浩 on 16/4/16.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "NetWorkRequestManager.h"

@implementation NetWorkRequestManager

+ (void)requestWithUrl:(NSURL *)url Type:(RequestType)type Params:(NSDictionary *)params ResultBlock:(ResultBlock)block{
    NSMutableString *urlStr = [NSMutableString string];
    if ([url isKindOfClass:[NSURL class]]) {
        [urlStr appendString:url.absoluteString];
    }else if ([url isKindOfClass:[NSString class]]){
        [urlStr appendString:(NSString *)url];
    }
    if (urlStr.length == 0) {
        NSError *error = [NSError errorWithDomain:@"EPA" code:111 userInfo:@{@"reason":@"你输入的网址不正确"}];
        block(nil,nil,error);
        return;
    }
    NetWorkRequestManager *manager = [NetWorkRequestManager new];
    NSString *paramsStr = [manager strWithParamsDict:params];
    switch (type) {
        case GET:{
            [urlStr appendString:paramsStr];
            [manager getRequestWithUrl:[NSURL URLWithString:urlStr] ResultBlock:block];
            break;
        }
        case POST:{
            [manager postRequestWithUrl:[NSURL URLWithString:urlStr] ParamsStr:paramsStr ResultBlock:block];
            break;
        }
        default:
            break;
    }
}

- (NSString *)strWithParamsDict:(NSDictionary *)dict{
    NSMutableString *paramsStr = [NSMutableString string];
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dict.allKeys) {
        [array addObject:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
    }
    [paramsStr appendString:[array componentsJoinedByString:@"&"]];
    return paramsStr;
}

- (void)getRequestWithUrl:(NSURL *)url ResultBlock:(ResultBlock)block{
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:block];
    [dataTask resume];
}

- (void)postRequestWithUrl:(NSURL *)url ParamsStr:(NSString *)paramsStr ResultBlock:(ResultBlock)block{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPBody = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:block];
    [dataTask resume];
}

@end
